package com.example.com.baruffini_mele.booking4u;



import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.*;

import com.example.com.baruffini_mele.booking4u.authorization.DatabaseHandler;
import com.example.com.baruffini_mele.booking4u.authorization.JoomlaPasswordHandler;
import com.example.com.baruffini_mele.booking4u.authorization.User;

public class SupplyCredentialsActivity extends Activity {
	
	private static final String TAG = "SupplyCredentialsActivity";	
	

    @Override
    /**
	 * Handles credentils storing.
	 * If a couple of credential is stored into the local database, it allows to update or
	 * delete it; if not, it allows to insert a new one.
	 * 
	 * @param savedInstanceState: the saved stato of the activity
	 */	
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        //layout retrieval
        setContentView(R.layout.activity_supply_credentials_layout);
        
        // checks if user exists in local database
        final DatabaseHandler db = new DatabaseHandler(this);
    	
    	final int existingUser = db.getUsersCount(); 
    	if(existingUser==1){
        
    	
    	// user exists: perhaps he wants to change his credentials
    		AlertDialog.Builder userExistsBuilder = new AlertDialog.Builder(SupplyCredentialsActivity.this);
    		// set title
    		userExistsBuilder.setTitle(R.string.user_exists_title);
        	// set dialog message
    		userExistsBuilder.setMessage(R.string.user_exists_text);
        	// DIALOG "USER EXISTS" set positive button - cancel alert dialog and update credentials
    		userExistsBuilder.setPositiveButton(R.string.user_exists_button_yes, new DialogInterface.OnClickListener() {
    			@Override
				public void onClick(DialogInterface dialog, int id) {
					// TODO Auto-generated method stub
					
					// if this button is clicked, just close
					// the dialog box and do nothing
					 dialog.cancel();
					 

					// show alert dialog "update or delete"
			   			
			  			AlertDialog.Builder updateOrDeleteBuilder = new AlertDialog.Builder(SupplyCredentialsActivity.this);
			       			// set title
			  			updateOrDeleteBuilder.setTitle(R.string.delete_or_update_title);
			           		// set dialog message
			  			updateOrDeleteBuilder.setMessage(R.string.delete_or_update_text);
			           		// DIALOG "DELETE OR UPDATE" set positive button
			  			updateOrDeleteBuilder.setPositiveButton(R.string.delete_or_update_button_yes, new DialogInterface.OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int id) {
									// TODO Auto-generated method stub
									
									// if this button is clicked, close
									// the dialog box turn back to main activity
									 dialog.cancel();
									 //Intent i = new Intent(getBaseContext(), MainActivity.class);
									 //startActivity(i);
									
					
								}
							});
			  		// DIALOG "DELETE OR UPDATE" set negative button
			  			updateOrDeleteBuilder.setNegativeButton(R.string.delete_or_update_button_no, new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int id) {
								// TODO Auto-generated method stub
								
								// if this button is clicked, delete user credentials, close
								// the dialog box  and turn back to main activity
								db.deleteAllUsers();
								 dialog.cancel();
								 Intent i = new Intent(getBaseContext(), MainActivity.class);
								 startActivity(i);
								
				
							}
						});
			           	// create alert dialog
			           	AlertDialog updateOrDeleteCredentials = updateOrDeleteBuilder.create();
			           	// show it
			           	updateOrDeleteCredentials.show();
					 
	 
					 
			}
			});
    		// DIALOG "USER EXISTS" set negative button - he does not want to change his credentials.
    		userExistsBuilder.setNegativeButton(R.string.user_exists_button_no, new DialogInterface.OnClickListener() {
    			@Override
				public void onClick(DialogInterface dialog, int id) {
					// TODO Auto-generated method stub
					
					// if this button is clicked, turn back to main activity and then restart
    				Intent i = new Intent(getBaseContext(), MainActivity.class);
					startActivity(i);
	
	
				}
			});
        	// create alert dialog
        	AlertDialog userExists = userExistsBuilder.create();
        	// show it
        	userExists.show();
    
    	}
    	
    	// end  case USER EXISTS on local db
    	
        
        //text box contents
        final EditText textUsername = (EditText) findViewById(R.id.editTextUsername);
        final EditText textPassword = (EditText) findViewById(R.id.editTextPassword);
        //save and connect button
        Button saveBtn = (Button)findViewById(R.id.buttonSave);
        Button clearBtn = (Button)findViewById(R.id.buttonSave);
        
        
        //on click listners
        
      
        
        
        //SAVE button listener
        saveBtn.setOnClickListener(new View.OnClickListener() {
            
        	public void onClick(View v) {
        		String stringUsername = "";	
        		String stringUserPassword = "";
        		// checkif  edittext empty
        		
        		// if edit text empty
        		
        		if ((textUsername.getText().toString().equals(""))||(textPassword.getText().toString().equals(""))){
        		
        			AlertDialog.Builder emptyFieldsBuilder = new AlertDialog.Builder(SupplyCredentialsActivity.this);
            		// set title
        			emptyFieldsBuilder.setTitle(R.string.empty_fields_title);
                	// set dialog message
        			emptyFieldsBuilder.setMessage(R.string.empty_fields_text);
                	// set positive button
        			emptyFieldsBuilder.setPositiveButton(R.string.empty_fields_button, new DialogInterface.OnClickListener() {
        				
        				@Override
        				public void onClick(DialogInterface dialog, int id) {
        					// TODO Auto-generated method stub
        					
        					// if this button is clicked, just close
        					// the dialog box and do nothing
        					 dialog.cancel();
        					
        					
        	
        				}
        			});
                	// create alert dialog
                	AlertDialog emptyFields = emptyFieldsBuilder.create();
                	// show it
                	emptyFields.show();	
        			
        			
        			
        			
        		
        		}else{ //if edit text not empty
        			stringUsername = textUsername.getText().toString().trim(); 
            		stringUserPassword = textPassword.getText().toString().trim();
    		
    		boolean authenticated = false;
    		// Authentication
    		
    		//Connection to remote database and hash retrieval
    		JoomlaPasswordHandler jph = new JoomlaPasswordHandler(stringUsername, stringUserPassword);
    		
    		 //request remote user hash and fill savedHash property
    		jph.postUserHashRequest();
    		if(!jph.getSavedHash().equals("0")){ // only if savedHash!=0 user exists in remote db
    			
    			
    		Log.v(TAG, "posted request");
         	jph.setUserSalt(jph.estractSalt(jph.getSavedHash()));
         	jph.setUserHash(jph.encryptLocalPassword(jph.getUserPassword()));
			
			//check match between two hashes
			Log.v(TAG, "userHash = "+jph.getUserHash());
			Log.v(TAG, "savedHash ="+jph.getSavedHash());
			
			 authenticated = jph.accessAuthentication();
			 
    		}//end savedHash==0 case
  		
    		if(authenticated==true){
    			User user = new User(1, stringUsername, stringUserPassword);
    			Log.v(TAG, "authentication succeeded");
    			
    			// get database access
    			DatabaseHandler dbh = new DatabaseHandler(getBaseContext());
    			
            	//SQLiteDatabase db = dbh.getWritableDatabase();
            	
            	
            	
            	// values to be inserted
            	//ContentValues values = new ContentValues();
            	//values.put("username",stringUsername);
            	//values.put("password",stringUserPassword);
            	
    			switch(existingUser){
    			// if user already exists, then update entry  			
            	case 1:
            		dbh.updateUser(user);
            		
            	break;
            	// if user does not exists, then insert entry	
            	case 0:
            	//insert
                	//long id = db.insert("users",null, values);
            		dbh.addUser(user);
      		    break;
    			}
    			
    			
    			
    			
		            		
            	// show alert dialog "OK right credentials"
    			
    			
    			
    			AlertDialog.Builder rightCredentialsBuilder = new AlertDialog.Builder(SupplyCredentialsActivity.this);
        			// set title
    			rightCredentialsBuilder.setTitle(R.string.right_credentials_title);
            		// set dialog message
    			rightCredentialsBuilder.setMessage(R.string.right_credentials_text);
            		// set positive button
    			rightCredentialsBuilder.setPositiveButton(R.string.right_credentials_button, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int id) {
						// TODO Auto-generated method stub
						
						// if this button is clicked, close
						// the dialog box and start next activity
						 dialog.cancel();
						 Intent i = new Intent(getBaseContext(), SelectRoomActivity.class);
						 startActivity(i);
						
		
					}
				});
            	// create alert dialog
            	AlertDialog alertCredentials = rightCredentialsBuilder.create();
            	// show it
            	alertCredentials.show();
            	
            	
    		
    		// if wrong cretentials
    		}else{
    			Log.v(TAG, "authentication failed");
    			
    		
    			
    			AlertDialog.Builder wrongCredentialsBuilder = new AlertDialog.Builder(SupplyCredentialsActivity.this);
        		// set title
    			wrongCredentialsBuilder.setTitle(R.string.wrong_credentials_title);
            	// set dialog message
    			wrongCredentialsBuilder.setMessage(R.string.wrong_credentials_text);
            	// set positive button
    			wrongCredentialsBuilder.setPositiveButton(R.string.wrong_credentials_button, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int id) {
						// TODO Auto-generated method stub
						
						// if this button is clicked, just close
						// the dialog box and do nothing
						 dialog.cancel();
						
						
		
					}
				});
            	// create alert dialog
            	AlertDialog alertCredentials = wrongCredentialsBuilder.create();
            	// show it
            	alertCredentials.show();
    		
    			
    		}
    		
    		
	
			
		}// end if edit text not empty
	

        	}
          
        	
        	
   	
        });	
        
    	
       
    }
    
 
    
    
    
    /*************/

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_supply_credentials_menu, menu);
        return(super.onCreateOptionsMenu(menu));
    }
    
    
    
    
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) 
        {
        	// if help selected
            case R.id.supplyCredentials_menu_home:
            	// start Main
               startActivity(new Intent(this, MainActivity.class));
            return true;
            
            
        }// end switch on menu item
        return(super.onOptionsItemSelected(item));
    }
    
}

